package marioarena;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class GameserverNotificationReceiver
 */
@WebServlet("/GameserverUpdateReceiver")
public class GameserverUpdateReceiver extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GameserverUpdateReceiver() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// This servlet should not be accessed by browsing; instead, it should only
		// be used for updating a connected server via HTTP POST-requests. Redirect.
		response.sendRedirect("ServerList");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// Process gameserver data
		try
		{
			String objectId = request.getParameter("objectid");

			if (objectId == null) // First time the gameserver has notified the webserver
			{
				String name = request.getParameter("name");
				String ip = request.getParameter("ip");
				int port = Integer.parseInt(request.getParameter("port"));
				int maxPlayers = Integer.parseInt(request.getParameter("maxplayers"));
				int currentPlayers = Integer.parseInt(request.getParameter("currentplayers"));
				String state = request.getParameter("state");
				System.out.println("Received state: " + state);

				// Insert the server
				DbConnection dbConnection = new DbConnection();
				objectId = dbConnection.insertServer(name, ip, port, maxPlayers, currentPlayers, state);

				// Return the objectid as response
				ServletOutputStream responseOutputStream = response.getOutputStream();
				responseOutputStream.print(objectId);
				responseOutputStream.flush();
			}
			else 
			{
				// Not the first time the gameserver has contacted the webserver. 
				// The gameserver is now aware of its object id, and only sends the object id
				// and variable data (like its current amount of players) to minimize data size.

				//First, check if the request if a state update
				String state = request.getParameter("state");
				if(state != null){
					int currentPlayers = Integer.parseInt(request.getParameter("currentplayers"));

					DbConnection dbConnection = new DbConnection();
					dbConnection.updateGameserver(objectId, currentPlayers, state);
				}
				else{
					//If request is not a state update, check if it is a score upload.
					String scoredata = request.getParameter("scoredata");
					updateScores(scoredata);
				}
			}
		}
		catch (Exception e){e.printStackTrace();}
	}

	/**
	 * Updates the scores of one or more player.
	 * @param scoredata The score data received via the HTTP POST-request.
	 */
	private void updateScores(String scoredata){
		System.out.println("received " + scoredata);
		String[] splitScoreData = scoredata.split(":");
		System.out.println("Found " + splitScoreData.length + " scores.");
		for(int i=0; i < splitScoreData.length; i++){
			try{
				String dataItem = splitScoreData[i];
				String[] splitDataItem = dataItem.split("#");
				if(splitDataItem.length == 2){ //WebId and score
					String webId = splitDataItem[0];
					int score = Integer.parseInt(splitDataItem[1]);
					//Update score for this player
					DbConnection dbConnection = new DbConnection();
					dbConnection.updateScore(webId, score);
					System.out.println("Player " + webId + " gains " + score + " score");
				}
			}
			catch(Exception e){}
		}
	}

}
